package pri.zxx.webdemo.config;

import jakarta.servlet.ServletOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import pri.zxx.webdemo.entity.vo.ResultData;
import pri.zxx.webdemo.entity.vo.ResultEnum;
import pri.zxx.webdemo.utils.GsonUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author Twilight
 * @desc
 * @createTime 2020-05-03-10:21
 */
//@Component
@Slf4j
public class CustomInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String remoteAddr = this.getIpAddr(request) + ",path:" + request.getRequestURI();
		log.warn("----->>访问ip：{}", remoteAddr);
		Object o = redisTemplate.opsForValue().get(remoteAddr);
		if (o != null) {
			redisTemplate.opsForValue().increment(remoteAddr);
			int num = Integer.parseInt(o.toString());
			if (num >= 10 && num < 15) {
				return responseInfo(response, new ResultData(ResultEnum.FAILED, "稍后重试"));
			} else if (num >= 15) {
				//超过次数
				//todo add to banned ips
				return responseInfo(response, new ResultData(ResultEnum.FAILED, "ip已被加入黑名单"));
			}
		} else {
			redisTemplate.opsForValue().set(remoteAddr, 1, 20, TimeUnit.SECONDS);
		}
		return true;
	}

	//返回用户信息
	private Boolean responseInfo(HttpServletResponse response, ResultData resultData) throws IOException {
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setCharacterEncoding("UTF-8");
		ServletOutputStream outputStream = response.getOutputStream();
		outputStream.write(GsonUtil.toJson(resultData).getBytes(StandardCharsets.UTF_8));
		outputStream.flush();
		return false;
	}

	//获取用户真实ip方法二
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x - forwarded - for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy - Client - IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL - Proxy - Client - IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
